package redteam.networktest;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class NetworkTest extends Activity {

	private String host = "192.168.0.6";
	private TextView status;
	private int port = 8002;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        status = (TextView)findViewById(R.id.status);
        status.setText("do something");

        Button btnRunServer = (Button)findViewById(R.id.runserver);
        btnRunServer.setOnClickListener(new Button.OnClickListener() {
        	public void onClick(View v) {
        		// run server
        		try {
        			ServerSocket serverSocket = new ServerSocket(port);

        			status.setText(status.getText() + " waiting");

        			Socket player1 = serverSocket.accept();

        			//status.setText(player1.getInetAddress().getHostAddress());
        			status.setText(status.getText() + " done");

        			DataInputStream dis = new DataInputStream(player1.getInputStream());

        			status.setText(status.getText()+ "" + dis.readInt());
        			status.setText(status.getText()+ "" + dis.readInt());
        			status.setText(status.getText()+ "" + dis.readInt());

        			player1.close();
        		}
        		catch (Exception ex) {
        			status.setText(status.getText() + ex.getMessage());
        		}
        	}
        });

        Button btnConnect = (Button)findViewById(R.id.connect);
        btnConnect.setOnClickListener(new Button.OnClickListener() {
        	public void onClick(View v) {
        		// connect to server
        		try {
        			Socket socket = new Socket(host, port);

        			DataInputStream fromServer = new DataInputStream(socket.getInputStream());
        			DataOutputStream toServer = new DataOutputStream(socket.getOutputStream());

        			status.setText("connected");

        			toServer.writeInt(1337);
        		}
        		catch (Exception ex) {
        			status.setText(ex.getMessage());
        		}
        	}
        });

    }
}